package com.myzf.ncov.utils;

import lombok.extern.slf4j.Slf4j;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;

/**
 * 获取数据的工具类
 *
 * @author limuyi
 * @version V1.0
 * Created by limuyi on 2020-02-01 14:37
 */
@Slf4j
public class GetDataUtil {

    /**
     * 请求
     *
     * @param requestUrl 请求url
     * @param requestArg 请求参数
     * @return
     */
    public static String request(String requestUrl, String requestArg) {
        BufferedReader reader;
        String result = null;
        StringBuilder sbf = new StringBuilder();
        requestUrl = requestUrl + "?" + requestArg;

        try {
            URL url = new URL(requestUrl);
            HttpURLConnection connection = (HttpURLConnection) url
                    .openConnection();
            connection.setRequestMethod("GET");
            InputStream is = connection.getInputStream();
            reader = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8));
            String strRead;
            while ((strRead = reader.readLine()) != null) {
                sbf.append(strRead);
            }
            reader.close();
            result = sbf.toString();
        } catch (Exception e) {
            log.error(e.getLocalizedMessage());
        }
        return result;
    }
}
